<?php

namespace App\Console\Commands;

use App\Model\Business\Schedule;
use App\Model\Business\ScheduleStuden;
use App\Model\Foundation\Student;
use App\Model\Foundation\Teacher;
use App\Model\System\Notice;
use App\Model\System\NoticeConfig;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

/**
 * 每小时运行一次
 *
 * Class ScanDaily
 * @package App\Console\Commands
 */
class ScanDaily extends Command
{
    /**
     * 如果DB用时间戳，设置为1，datetime，设置为0
     */
    const  isStemp = 0;

    protected $signature = 'Notice:Daily';
    protected $description = 'message scanner';

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     * @return mixed
     */
    public function handle()
    {
        # 获取通知配置列表
        $items = $this->getNoticeConfig();
        foreach ($items as $item){
            # 查询符合该用户的课节信息
            $sids = $this->getUserSchedules($item['uid'],$item['utype']);
            if(!empty($sids)){
                $this->makeMessage($item['uid'], $sids,$item['utype']);
            }
        }
    }


    /**
     * 计算第二天
     * 第二天，是真是的第二天，今天的24:00 - 明天的24：00
     * @return array
     */
    protected function getNextDay()
    {
        static $set = 0, $start = null, $end = null;
        if(!$set){
            $set = 1;
            $next = time()+86400;
            if(self::isStemp){
                $start = strtotime(date('Y-m-d', $next));
                $end =  strtotime(date('Y-m-d', $next))+86400;
            }else{
                $start = date('Y-m-d H:i:s', strtotime(date('Y-m-d', $next)));
                $end = date('Y-m-d H:i:s', strtotime(date('Y-m-d', $next))+86400);
            }
        }
        return [$start, $end];
    }


    /**
     * 获取明天的课程列表id
     */
    protected function getTomorrowSchedules()
    {
        static $sids = [];

        if(empty($sids)){
            list($start, $end) = $this->getNextDay();
            $sids = Schedule::where('begintime', '>=', $start)
                            ->where('endtime', '<=', $end)
                            ->pluck('scheduleid')->toarray();
        }
        return $sids;
    }


//    /**
//     * 检查学生课节数
//     * @param $studentuid
//     */
//    protected function getStudentSchedules($studentuid)
//    {
//        $sids = $this->getTomorrowSchedules();
//        $mySids = ScheduleStuden::whereIn('scheduleid', $sids)
//                            ->where('studentuid', $studentuid)
//                            ->pluck('scheduleid')
//                            ->toarray();
//        return $mySids;
//    }

    /**
     * 检查用户课节数
     * @param $studentuid
     */
    protected function getUserSchedules($uid,$type)
    {
        $sids = $this->getTomorrowSchedules();
        if($type == 1){
            $mySids = Schedule::whereIn('scheduleid',$sids)
                    ->where('teacheruid',$uid)
                    ->pluck('scheduleid')
                    ->toarray();
        }else{
            $mySids = ScheduleStuden::whereIn('scheduleid', $sids)
                ->where('studentuid', $uid)
                ->pluck('scheduleid')
                ->toarray();
        }

        return $mySids;
    }


    /**
     * 获取当前小时
     * @return false|string
     */
    protected function now()
    {
        return date('H');
    }

    /**
     * 获取本次需要提醒的用户通知配置列表
     */
    protected function getNoticeConfig()
    {
        $now = $this->now();
        $items = NoticeConfig::where('perday', $now)
                            ->where('ntype', 1)
                            ->get()->toarray();
        return $items;
    }

    /**
     * 把消息记录到消息库
     */
    protected function makeMessage($uid, $sids, $type)
    {
        $msg = ['jsonable'=>'1', 'to'=>'','title'=>'上课提醒','body'=>""];
        if($type == 1){
            $user = Teacher::where('teacheruid', $uid)->first();
            $username = $user->lastname;
            $userid = $user->userid;
        }else{
            $user = Student::where('studentuid', $uid)->first();
            $username = $user->name;
            $userid = $user->userid;
        }


        $schedules = Schedule::find($sids);

        foreach ($schedules as $item){
            $obj['username'] = $username;
            $obj['coursename'] = $item->name;
            if(self::isStemp){
                $obj['date'] = date('Y-m-d H:i:s', $item->begintime);
            }else{
                $obj['date'] = $item->begintime;
            }
            $obj['remark'] = '';

            # 存储
            $msg['to'] = $userid;
            $msg['body'] = json_encode($obj,JSON_UNESCAPED_UNICODE);
            $notice = new Notice($msg);
            $notice->save();
        }
    }


}
